﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using VmcRemote.Common.Interfaces;
using System.Xml.Linq;
using System.Reflection;

namespace VmcRemote.Common
{
    public abstract class MediaCenterBase : IMediaCenter
    {
        string loadedConfig;
        Dictionary<RemoteCommand, string> commandMappings = new Dictionary<RemoteCommand, string>();

        public string ConfigurationXml { get; set; }

        public abstract bool SupportsConnection(Type connectionType);

        private void LoadConfig()
        {
            XDocument doc = XDocument.Parse(ConfigurationXml);
            var commands = from element in doc.Descendants("command")
                           where element.Parent.Attributes("type").Count() == 1 
                            && ((string)element.Parent.Attribute("type")).Equals("MceController")
                            && element.Attributes("name").Count() == 1
                            && element.Attributes("text").Count() == 1
                           select new
                           {
                               CommandName = (string)element.Attribute("name"),
                               CommandText = (string)element.Attribute("text")
                           };

            foreach (var currentCommand in commands)
            {
                if (string.IsNullOrEmpty(currentCommand.CommandName)) continue;

                Type commandType = typeof(RemoteCommand);
                try
                {
                    object value = System.Enum.Parse(typeof(RemoteCommand), currentCommand.CommandName, false);
                    if (value != null)
                        commandMappings.Add((RemoteCommand)value, currentCommand.CommandText);
                }
                catch { }
            }

            loadedConfig = ConfigurationXml;
        }

        public virtual string GetCommandString(RemoteCommand command)
        {
            if (loadedConfig != ConfigurationXml)
                LoadConfig();
            return commandMappings[command];
        }
    }
}
